from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from zope.component import getUtility
from zope.component import getMultiAdapter
from Acquisition import aq_inner
from plone.memoize.instance import memoize
from my315ok.fangcan.interfaces import Ihouse

from zope.i18n.interfaces import ITranslationDomain
from zope.component import queryUtility

from Products.CMFCore.interfaces import ISiteRoot
from Products.AdvancedQuery import Eq, Between, Le
#from ely.advancedquery.interfaces import IAdvancedCatalogQuery
#advancedquery = getUtility(IAdvancedCatalogQuery)

from my315ok.fangcan import fangcanMessageFactory as _


class IfangcansearchView(Interface):
    """
    fangcansearch view interface
    """

    def test():
        """ test method"""


class fangcansearchView(BrowserView):
    """
    fangcansearch browser view
    """
    implements(IfangcansearchView)

    def __init__(self, context, request):
        self.context = context
        self.request = request

    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def portal(self):
        return getToolByName(self.context, 'portal_url').getPortalObject()

    def query(self):
        """
        compose query string
        
        """
        portal = getUtility(ISiteRoot)
        catalog = getToolByName(portal, 'portal_catalog')

        if "SearchableText" in self.request.form.keys():
            term = self.request.form["SearchableText"]
            term = term.strip()
            if len(term)!=0:
                query = Eq("SearchableText",term) | Eq('Description',term)
                return query
                
        raw = self.request["QUERY_STRING"]
        if len(raw) != 0:
            phase = raw.split("&")
            aq = catalog.makeAdvancedQuery({'review_state': 'published'})
#            import pdb
#            pdb.set_trace()
            for st2 in phase:                
                st = st2.split("=")
                pa = st[0]
                val = st[-1]
            
                if "-" in val:
#                op = Between
                    low = val.split("-")[0]
                    hight = val.split("-")[-1]
                    query = Between(pa,float(low),float(hight))
                
                else:
#                op = Eq
                    query = Eq(pa, val)
#                aq = query
                aq &= query 
            return query
    @memoize   
    def results(self):
#        import pdb
#        pdb.set_trace()
        portal = getUtility(ISiteRoot)
        catalog = getToolByName(portal, 'portal_catalog')
        query = self.query()
        if query == "" or query ==None:
            return []
        result = catalog.evalAdvancedQuery(query)
        return result
#        results = ADQ(self.query(), sortSpecs=())
#        return results 

    def getURL(self,brain):
        path = brain.getPath()
#        return brain.getURL()
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        root = portal_state.navigation_root_url()
        d = path.split("/")
        return  root + "/" + "/".join(d[2:])
      
    @memoize
    def getbigarea(self):
#        import pdb
#        pdb.set_trace()
        portal = getUtility(ISiteRoot)
        catalog = getToolByName(portal, 'portal_catalog')  
        brains = catalog(object_provides=Ihouse.__identifier__)
        lt = []
        for ss in brains:
            t = ss.Bigarea.strip()
            try:
                lent = len(t)
            except:
                continue

            if lent !=0 and t not in lt:
                lt.append(t)
#                continue
        return lt
    @memoize
    def getArea(self):
#        import pdb
#        pdb.set_trace()
        portal = getUtility(ISiteRoot)
        catalog = getToolByName(portal, 'portal_catalog')  
        brains = catalog(object_provides=Ihouse.__identifier__)
        lt = []
        for ss in brains:
            t = ss.Area.strip()
            try:
                lent = len(t)
            except:
                continue

            if lent !=0 and t not in lt:
                lt.append(t)
#                continue
        return lt
    def translates(self,item):
#        import pdb
#        pdb.set_trace()      
        
        util = queryUtility(ITranslationDomain, 'my315ok.fangcan')    
        tted = util.translate(item,target_language="zh",
                                       default="yuhu")           
        return tted
    
    def getImage(self,brain,scale="thumb"):
        
        if scale=="orig":
            ext = "/image"
        else:
            ext = "/image_%s" % scale
        
        base = self.getURL(brain)
        title = brain.Title
        url = base + ext
        portal = self.portal
#        import pdb
#        pdb.set_trace()
        p_url = portal.absolute_url()
        existimg = portal.unrestrictedTraverse(url, default=None)
        if existimg == None:
            url = p_url + "/++resource++fcwatermark.jpg"                            
        htmltag = "<img src='%s' alt='%s' />" %(url,title)
        return htmltag
                
        
    def test(self,t,a,b):
        """ test method"""   
        if t:
            return a
        else:
            return b
         


     
